package com.authine.cloudpivot.web.api.common;

import com.authine.cloudpivot.web.api.controller.runtime.FormRuntimeController;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author pancw
 * @description
 * @date 2020/06/17
 */
@Slf4j
public class XmlUtil {
    private static final Logger log = LoggerFactory.getLogger(XmlUtil.class);
    /**
     * java对象转换为xml文件
     *
     * @param obj xml文件路径
     * @param load    java对象.Class
     * @return xml文件的String
     * @throws JAXBException
     */
    public static String beanToXml(Object obj, Class<?> load) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(load);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }

    /**
     * 将String类型的xml转换成对象
     */
    public static Object convertXmlStrToObject(Class clazz, String xmlStr) throws JAXBException {
        Object xmlObject = null;
        log.info("==需要转化的xmlstr==="+xmlStr);
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
            return xmlObject;
    }

}
